const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;

const app = express();
const PORT = 3001;

// 中间件
app.use(cors()); // 允许跨域请求
app.use(express.json()); // 解析JSON请求体
app.use(express.static('public')); // 静态文件服务

// 数据文件路径
const DATA_DIR = path.join(__dirname, 'data');

// 确保数据目录存在
async function ensureDataDir() {
  try {
    await fs.access(DATA_DIR);
  } catch {
    await fs.mkdir(DATA_DIR, { recursive: true });
  }
}

// 通用数据读取函数
async function readJsonFile(filename) {
  try {
    const filePath = path.join(DATA_DIR, filename);
    const data = await fs.readFile(filePath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.log(`文件 ${filename} 不存在，返回空数组`);
    return [];
  }
}

// 通用数据写入函数
async function writeJsonFile(filename, data) {
  const filePath = path.join(DATA_DIR, filename);
  await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf8');
}

// ==================== API 路由 ====================

// 1. 领养案例 API
app.get('/api/adoption-cases', async (req, res) => {
  try {
    const cases = await readJsonFile('adoptionCases.json');
    const { search, page = 1, pageSize = 6 } = req.query;
    
    let filteredCases = cases;
    if (search) {
      filteredCases = cases.filter(item => 
        item.name.includes(search) || 
        item.adopter?.includes(search) || 
        item.description?.includes(search)
      );
    }
    
    const startIndex = (page - 1) * pageSize;
    const paginatedCases = filteredCases.slice(startIndex, startIndex + parseInt(pageSize));
    
    res.json({
      success: true,
      data: paginatedCases,
      total: filteredCases.length,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(filteredCases.length / pageSize)
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取领养案例失败', error: error.message });
  }
});

app.get('/api/adoption-cases/:id', async (req, res) => {
  try {
    const cases = await readJsonFile('adoptionCases.json');
    const caseItem = cases.find(c => c.id === parseInt(req.params.id));
    
    if (!caseItem) {
      return res.status(404).json({ success: false, message: '案例不存在' });
    }
    
    res.json({ success: true, data: caseItem });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取案例详情失败', error: error.message });
  }
});

// 2. 宠物知识 API
app.get('/api/pet-knowledge', async (req, res) => {
  try {
    const articles = await readJsonFile('knowledgeArticles.json');
    const { search, page = 1, pageSize = 10 } = req.query;
    
    let filteredArticles = articles;
    if (search) {
      filteredArticles = articles.filter(item => 
        item.title.includes(search) || 
        item.content?.includes(search)
      );
    }
    
    const startIndex = (page - 1) * pageSize;
    const paginatedArticles = filteredArticles.slice(startIndex, startIndex + parseInt(pageSize));
    
    res.json({
      success: true,
      data: paginatedArticles,
      total: filteredArticles.length,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(filteredArticles.length / pageSize)
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取宠物知识失败', error: error.message });
  }
});

// 3. 宠物新闻 API
app.get('/api/pet-news', async (req, res) => {
  try {
    const articles = await readJsonFile('newsArticles.json');
    const { search, page = 1, pageSize = 10 } = req.query;
    
    let filteredArticles = articles;
    if (search) {
      filteredArticles = articles.filter(item => 
        item.title.includes(search) || 
        item.content?.includes(search)
      );
    }
    
    const startIndex = (page - 1) * pageSize;
    const paginatedArticles = filteredArticles.slice(startIndex, startIndex + parseInt(pageSize));
    
    res.json({
      success: true,
      data: paginatedArticles,
      total: filteredArticles.length,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(filteredArticles.length / pageSize)
    });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取宠物新闻失败', error: error.message });
  }
});

// 4. 文章详情 API (知识+新闻)
app.get('/api/articles/:id', async (req, res) => {
  try {
    const [knowledgeArticles, newsArticles] = await Promise.all([
      readJsonFile('knowledgeArticles.json'),
      readJsonFile('newsArticles.json')
    ]);
    
    const allArticles = [...knowledgeArticles, ...newsArticles];
    const article = allArticles.find(a => a.id === parseInt(req.params.id));
    
    if (!article) {
      return res.status(404).json({ success: false, message: '文章不存在' });
    }
    
    res.json({ success: true, data: article });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取文章详情失败', error: error.message });
  }
});

// 5. 救助案例 API
app.get('/api/rescue-cases/:type', async (req, res) => {
  try {
    const { type } = req.params; // cats, dogs, others
    const cases = await readJsonFile(`${type}.json`);
    
    res.json({ success: true, data: cases });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取救助案例失败', error: error.message });
  }
});

// 6. 留言板 API
app.get('/api/guestbook', async (req, res) => {
  try {
    const messages = await readJsonFile('guestbook.json');
    // 只返回已审核通过的留言
    const approvedMessages = messages.filter(msg => msg.status === 'approved');
    
    res.json({ success: true, data: approvedMessages });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取留言失败', error: error.message });
  }
});

app.post('/api/guestbook', async (req, res) => {
  try {
    const { title, name, tel, email, address, content } = req.body;
    
    // 基础验证
    if (!name || !tel || !content) {
      return res.status(400).json({ success: false, message: '姓名、手机和留言内容不能为空' });
    }
    
    const messages = await readJsonFile('guestbook.json');
    const newMessage = {
      id: Date.now(), // 简单的ID生成
      title: title || '无标题',
      name,
      tel,
      email: email || '',
      address: address || '',
      content,
      status: 'pending', // 待审核
      createTime: new Date().toISOString(),
      replyContent: '', // 管理员回复
      replyTime: null
    };
    
    messages.push(newMessage);
    await writeJsonFile('guestbook.json', messages);
    
    res.json({ success: true, message: '留言提交成功，等待审核', data: newMessage });
  } catch (error) {
    res.status(500).json({ success: false, message: '提交留言失败', error: error.message });
  }
});

// 7. 联系信息 API
app.get('/api/contact-info', async (req, res) => {
  try {
    const contactInfo = await readJsonFile('contactInfo.json');
    res.json({ success: true, data: contactInfo });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取联系信息失败', error: error.message });
  }
});

// 8. 网站配置 API
app.get('/api/site-config', async (req, res) => {
  try {
    const config = await readJsonFile('siteConfig.json');
    res.json({ success: true, data: config });
  } catch (error) {
    res.status(500).json({ success: false, message: '获取网站配置失败', error: error.message });
  }
});

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({ 
    success: true, 
    message: '流浪动物之家 API 服务正常运行', 
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// 启动服务器
async function startServer() {
  await ensureDataDir();
  
  app.listen(PORT, () => {
    console.log('🐾 流浪动物之家 API 服务器启动成功!');
    console.log(`📡 API地址: http://localhost:${PORT}`);
    console.log(`💚 健康检查: http://localhost:${PORT}/api/health`);
    console.log('📋 可用接口:');
    console.log('   GET  /api/adoption-cases     # 领养案例');
    console.log('   GET  /api/pet-knowledge      # 宠物知识');
    console.log('   GET  /api/pet-news          # 宠物新闻');
    console.log('   GET  /api/articles/:id      # 文章详情');
    console.log('   GET  /api/rescue-cases/:type # 救助案例');
    console.log('   GET  /api/guestbook         # 留言列表');
    console.log('   POST /api/guestbook         # 提交留言');
    console.log('   GET  /api/contact-info      # 联系信息');
    console.log('   GET  /api/site-config       # 网站配置');
    console.log('================================');
  });
}

startServer().catch(console.error);

module.exports = app;
